import axios from 'axios'
import {ElMessage,ElLoading} from "element-plus"

const instance = axios.create({
    headers: {'content-type': 'application/json'},
    timeout: 1000 * 3, // 设置超时时间10s
    baseURL: '/',
})
// 添加请求拦截器
instance.interceptors.request.use(function (config) {
    // 在发送请求之前做些什么
    return config
}, function (error) {
    // 对请求错误做些什么
    return Promise.reject(error)
})
// 添加响应拦截器
instance.interceptors.response.use(function (response) {
    return response.data
}, function (error) {
    return Promise.reject(error)
})
export const get = (url, params, config = {}) => {
    const  loadState = ElLoading.service({});
    return new Promise((resolve, reject) => {
        instance({
            method: 'get',
            url,
            params,
            ...config
        }).then(response => {
            resolve(response)
            loadState.close();
        }).catch(error => {
            loadState.close();
            if(error.request.status == 404){
                ElMessage.error({
                    showClose: true,
                    message: '数据加载失败',
                    type: 'success'
                })
            }
            reject(error)
        })
    })
}
export const post = (url, data, config = {}) => {
    return new Promise((resolve, reject) => {
        instance({
            method: 'post',
            url,
            data,
            ...config
        }).then(response => {
            resolve(response)
        }).catch(error => {
            if(error.request.status == 404){
                ElMessage.error({
                    showClose: true,
                    message: '数据加载失败',
                    type: 'success'
                })
            }
            reject(error)
        })
    })
}

export const axiosInstance = instance;

